# -*- coding: utf-8 -*-
from utils import gen_data
from sklearn.cluster import KMeans
from sklearn.svm import SVC
from sklearn.metrics import hamming_loss
import numpy as np


def correct_pred(X, y, n_clusters=5):
    km = KMeans(n_clusters=n_clusters)
    cluster_pred = km.fit_predict(test_data)

    clusters = []       # 记录每个簇中对应的数据下标
    clu_pred = []       # 记录每个簇中数据对应的预测类别
    inx = []
    for i in range(n_clusters):
        clusters.append([])
        clu_pred.append([])
    for i in range(len(cluster_pred)):
        clusters[cluster_pred[i]].append(i)
        clu_pred[cluster_pred[i]].append(y[i])
    labels = [1 if np.sum(i) > 0 else -1 for i in clu_pred]        # 记录每个簇对应的预测类别，按照多数投票
    for i in range(n_clusters):
        tmp = [clusters[i][j] for j in range(len(clu_pred[i]))if clu_pred[i][j] == labels[i]]
        inx += tmp
    return inx


if __name__ == '__main__':
    path = r'../data/csv/'
    name = 'breast_cancer.csv'
    train_data, train_label, test_data, test_label, labeled_data, labeled_label, unlabeled_data, unlabeled_label \
        = gen_data(path+name, unlabeled_rate=0.8, random_state=919)

    estimator = SVC()
    estimator.fit(train_data, train_label)
    test_pred = estimator.predict(test_data)
    loss = hamming_loss(test_label, test_pred)
    print(loss)

    losses = []
    for i in range(50):
        correct_inx = correct_pred(test_data, test_pred, 10)
        correct_loss = hamming_loss(test_label[correct_inx], test_pred[correct_inx])
        losses.append(correct_loss)
    print(np.average(losses))


